//
//  PhotosViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/12.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "PhotosViewController.h"
#import "PhotoCollectionViewCell.h"
#import "PhotoCollectionViewFlowLaout.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "PhotoViewModel.h"
#import <UIImageView+AFNetworking.h>

@interface PhotosViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate,UIImagePickerControllerDelegate,
UINavigationControllerDelegate>

@property (nonatomic ,weak) IBOutlet UIView *navView;
@property (nonatomic ,weak) IBOutlet UICollectionView *collectionView;
@property (nonatomic ,weak) IBOutlet UIButton *editButton;
@property (nonatomic ,assign) BOOL isEditing;

@property (nonatomic ,weak) IBOutlet UIView *bottomView;
@property (nonatomic ,weak) IBOutlet NSLayoutConstraint *heightConstraint;
@property (nonatomic ,strong) PhotoViewModel *viewModel;
@property (nonatomic ,strong) NSMutableArray *selectedArray;

@property (nonatomic ,weak) IBOutlet UIButton *removeButton;
@property (nonatomic ,weak) IBOutlet UIButton *addButton;


- (IBAction)dismissSelf:(id)sender;

@end


static NSString *reuseIdentify = @"Cell";

@implementation PhotosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    _collectionView.delegate = self;
    
    UINib *nib  = [UINib nibWithNibName:NSStringFromClass([PhotoCollectionViewCell class]) bundle:nil];
    _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentify];
    
    
    PhotoCollectionViewFlowLaout *layout = [[PhotoCollectionViewFlowLaout alloc] init];

    [_collectionView setCollectionViewLayout:layout];
    
    _heightConstraint.constant = 0;
    _bottomView.hidden = YES;
    _isEditing = NO;
    _selectedArray = [NSMutableArray array];
    
    _viewModel = [[PhotoViewModel alloc] init];
    @weakify(self);
    [[_editButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *button) {
        @strongify(self);
        if ([button.titleLabel.text isEqualToString:@"保存"]) {
            [button setTitle:@"编辑" forState:UIControlStateNormal];
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:1];
            _heightConstraint.constant =0;
            self.bottomView.hidden = YES;
            [UIView commitAnimations];
            _isEditing = NO;
            [_selectedArray removeAllObjects];
            [_collectionView reloadData];
            
            
        }else{
            [UIView beginAnimations:nil context:nil];

            [button setTitle:@"保存" forState:UIControlStateNormal];
            _heightConstraint.constant =44;
            self.bottomView.hidden = NO;
            [UIView commitAnimations];
            _isEditing = YES;
        }
        
        
    }];
    
    
    
    [[_removeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        
        if ([_selectedArray count]>0) {
            [self.viewModel removeItemsInArray:_selectedArray];
            [self.viewModel fetchDatazWithUser:nil];
        }else{
        
        
        }
        
        
    }];
    
   
    [[[_addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"本地相册",@"立即拍照", nil];
        
        [actionSheet showInView:self.view];
        
    }];
    
    
    [[RACObserve(_viewModel, hasLoaded) subscribeOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        [_collectionView reloadData];
    }];
    
    
    
    
    [_viewModel fetchDatazWithUser:nil];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dismissSelf:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_viewModel numberOfRowsInSection:section];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentify forIndexPath:indexPath];
    
    NSDictionary *dic = [_viewModel dictionaryForItemAtIndexPath:indexPath];
    [cell.imageView setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"image"]] placeholderImage:[UIImage imageNamed:@"hlr"]];
    cell.selectedImageView.hidden = ![_selectedArray containsObject:indexPath];
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((collectionView.frame.size.width-20)/3.0,(collectionView.frame.size.width-20)/3.0*1.1);
    

}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
    
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_isEditing) {
        
        if ([_selectedArray containsObject:indexPath]) {
            [_selectedArray removeObject:indexPath];
        }else{
            [_selectedArray addObject:indexPath];
        }
        [collectionView reloadItemsAtIndexPaths:@[indexPath]];
        return;
    }
    
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    switch (buttonIndex) {
        case 0:
            
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            
            break;
        case 1:
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            break;
        default:
            break;
    }
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image =  [info valueForKey:@"UIImagePickerControllerOriginalImage"];
    
    [_viewModel addPhoto:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

@end
